<script setup>
import { ref, onMounted, computed } from "vue";
import { saveCredentials, saveSkills } from "../../../api/resume.js";

// 页面参数
const pageType = ref(""); // credentials 或 skills
const pageTitle = ref("");
const tipText = ref("");
const maxTags = 30; // 最大标签数量
const maxTagLength = 15; // 单个标签最大长度

// 数据状态
const tags = ref([]); // 当前标签列表
const inputText = ref(""); // 输入框内容

// 计算属性
const tagCount = computed(() => `${tags.value.length}/${maxTags}`);
const canAddTag = computed(() => tags.value.length < maxTags);
const isInputValid = computed(() => {
  const text = inputText.value.trim();
  return text.length > 0 && text.length <= maxTagLength && !tags.value.includes(text);
});

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 添加标签
const addTag = () => {
  const text = inputText.value.trim();

  if (!text) {
    uni.showToast({
      title: "请输入内容",
      icon: "none",
    });
    return;
  }

  if (text.length > maxTagLength) {
    uni.showToast({
      title: `内容长度不能超过${maxTagLength}个字符`,
      icon: "none",
    });
    return;
  }

  if (tags.value.includes(text)) {
    uni.showToast({
      title: "内容已存在",
      icon: "none",
    });
    return;
  }

  if (tags.value.length >= maxTags) {
    uni.showToast({
      title: `最多只能添加${maxTags}个`,
      icon: "none",
    });
    return;
  }

  tags.value.push(text);
  inputText.value = "";
};

// 移除标签
const removeTag = (index) => {
  tags.value.splice(index, 1);
};

// 保存标签
const saveTags = async () => {
  try {
    uni.showLoading({
      title: "保存中...",
    });

    // 将标签数组转换为逗号分隔的字符串
    const tagsString = tags.value.join(',');

    if (pageType.value === 'credentials') {
      await saveCredentials(tagsString);
    } else if (pageType.value === 'skills') {
      await saveSkills(tagsString);
    }

    uni.hideLoading();
    
    uni.showToast({
      title: "保存成功",
      duration: 1500,
      success() {
        setTimeout(() => {
          // 触发简历刷新事件
          uni.$emit("refreshResume");
          uni.navigateBack();
        }, 1500);
      },
    });
  } catch (error) {
    uni.hideLoading();
    console.error("保存失败:", error);
    uni.showToast({
      title: "保存失败，请重试",
      icon: "none",
    });
  }
};

// 输入框回车事件
const onInputConfirm = () => {
  if (isInputValid.value && canAddTag.value) {
    addTag();
  }
};

// 页面加载
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  const options = currentPage.options || {};

  // 设置页面类型和标题
  pageType.value = options.type || 'credentials';
  
  if (pageType.value === 'credentials') {
    pageTitle.value = "资格证书";
    tipText.value = "添加您所获得的资格证书";
  } else if (pageType.value === 'skills') {
    pageTitle.value = "专业技能";
    tipText.value = "优先填写与求职岗位最匹配的技能,特长";
  }

  // 从 URL 参数获取已有标签
  if (options.value) {
    const existingTagsString = decodeURIComponent(options.value);
    if (existingTagsString) {
      const existingTagsArray = existingTagsString
        .split(",")
        .filter((tag) => tag.trim());
      tags.value = [...existingTagsArray];
    }
  }

  console.log("页面初始化完成:", {
    type: pageType.value,
    title: pageTitle.value,
    tags: tags.value
  });
});
</script>

<template>
  <view class="credentials-skills-container">
    <!-- 页头 -->
    <view class="header">
      <view class="header-content">
        <view class="back-btn" @click="goBack">
          <image
            class="back-icon"
            src="/static/icons/candidate/pre_page.png"
          ></image>
        </view>
        <view class="header-title">{{ pageTitle }}</view>
        <view class="save-btn" @click="saveTags">
          <text class="save-text">保存</text>
        </view>
      </view>
    </view>

    <!-- 内容区域 -->
    <view class="content">
      <!-- 标题和计数 -->
      <view class="title-section">
        <view class="title-row">
          <text class="main-title">{{ pageTitle }}</text>
          <text class="count-text">{{ tagCount }}</text>
        </view>
      </view>

      <!-- 提示信息 -->
      <view class="tip-section">
        <text class="tip-text">{{ tipText }}</text>
      </view>

      <!-- 输入区域 -->
      <view class="input-section">
        <view class="input-wrapper">
          <input
            class="tag-input"
            v-model="inputText"
            :placeholder="`请输入${pageTitle}`"
            :maxlength="maxTagLength"
            @confirm="onInputConfirm"
          />
          <view
            class="add-btn"
            :class="{ disabled: !isInputValid || !canAddTag }"
            @click="addTag"
          >
            <text class="add-text">添加</text>
          </view>
        </view>
      </view>

      <!-- 标签列表 -->
      <view class="tags-section" v-if="tags.length > 0">
        <view class="tags-container">
          <view class="tag-item" v-for="(tag, index) in tags" :key="index">
            <text class="tag-text">{{ tag }}</text>
            <view class="remove-btn" @click="removeTag(index)">
              <text class="remove-text">×</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-section" v-else>
        <text class="empty-text">暂无{{ pageTitle }}，请添加{{ pageTitle }}</text>
      </view>
    </view>
  </view>
</template>

<style scoped lang="less">
.credentials-skills-container {
  background-color: #ffffff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

/* 页头样式 */
.header {
  background-color: #ffffff;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  height: 88rpx;
  padding-top: calc(20rpx + var(--status-bar-height, 0));
  position: relative;
}

.back-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.back-icon {
  width: 48rpx;
  height: 48rpx;
}

.header-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #333333;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}

.save-btn {
  width: 80rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.save-text {
  font-size: 32rpx;
  color: #00bdb4;
  font-weight: 500;
}

/* 内容区域 */
.content {
  flex: 1;
  padding: 40rpx 30rpx;
}

/* 标题区域 */
.title-section {
  margin-bottom: 30rpx;
}

.title-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.main-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.count-text {
  font-size: 28rpx;
  color: #666666;
}

/* 提示区域 */
.tip-section {
  margin-bottom: 40rpx;
}

.tip-text {
  font-size: 28rpx;
  color: #999999;
  line-height: 40rpx;
}

/* 输入区域 */
.input-section {
  margin-bottom: 40rpx;
}

.input-wrapper {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.tag-input {
  flex: 1;
  height: 80rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333333;
  background-color: #ffffff;

  &::placeholder {
    color: #999999;
  }

  &:focus {
    border-color: #00bdb4;
  }
}

.add-btn {
  width: 120rpx;
  height: 80rpx;
  background-color: #00bdb4;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &.disabled {
    background-color: #cccccc;
  }
}

.add-text {
  font-size: 28rpx;
  color: #ffffff;
  font-weight: 500;
}

/* 标签区域 */
.tags-section {
  flex: 1;
}

.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.tag-item {
  display: flex;
  align-items: center;
  background-color: #46b4b3;
  border-radius: 30rpx;
  padding: 12rpx 24rpx;
  max-width: 400rpx;
}

.tag-text {
  font-size: 26rpx;
  color: #ffffff;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.remove-btn {
  margin-left: 16rpx;
  width: 32rpx;
  height: 32rpx;
  background-color: #666666;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.remove-text {
  font-size: 24rpx;
  color: #ffffff;
  font-weight: 600;
  line-height: 1;
}

/* 空状态 */
.empty-section {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}
</style>

